package v1

import (
	"chat/app"
	"chat/app/common"
	"chat/app/dao"
	"chat/app/model"
	"chat/app/service"
	"chat/utils"
	"context"
	"fmt"
	"github.com/go-playground/validator/v10"
	"strconv"
	"strings"
)

type friendAdd struct {
	Mobile string `from:"mobile" validate:"required,min=11,max=20"`
}

// AddFriendService 添加好友
func AddFriendService(ctx context.Context, c *app.Context) any {
	// 创建返回信息
	data := make(map[string]interface{})
	code := common.SUCCESS

	mobile := c.PostForm("mobile")
	memo := c.PostForm("memo")
	// 验证参数
	valid := validator.New()
	a := friendAdd{
		Mobile: mobile,
	}
	ok := valid.Struct(a)
	if ok != nil {
		// 翻译成中文
		trans := utils.ValidateTransInit(valid)
		verrs := ok.(validator.ValidationErrors)
		errs := make(map[string]string)
		for key, value := range verrs.Translate(trans) {
			errs[key[strings.Index(key, ".")+1:]] = value
		}
		fmt.Println(errs)
		//fmt.Printf("Err(s):\n%+v\n", ok)
		return common.Response(code, common.GetMsg(code), data)
	}

	// 查找好友
	userWhere := "mobile = ?"
	userArgs := []any{mobile}
	friend, rowsAffected := dao.UserGetOne(userWhere, userArgs...)
	if !rowsAffected {
		return common.Response(common.ERROR, "您要添加的好友不存在", data)
	}
	receiveId := friend.Id // 好友id

	// 我自己 uid
	uid := c.UserInfo["uid"]
	uidInt64 := uid.(int64)
	if uidInt64 == receiveId {
		return common.Response(common.ERROR, "不能添加自己为好友", data)
	}

	// 检查是否已经是好友
	where := "owner_id = ? and receive_id = ? and cate = ?"
	args := []any{
		uidInt64,
		receiveId,
		model.ConcatCateUser,
	}
	_, friendRowsAffected := dao.ContactGetOne(where, args...)
	if friendRowsAffected {
		return common.Response(common.ERROR, "该好友已经添加过了", data)
	}

	// 互加好友 开启事务
	addContact1 := model.Contact{
		OwnerId:   uidInt64,
		ReceiveId: receiveId,
		Cate:      model.ConcatCateUser,
		Memo:      memo,
	}
	addContact2 := model.Contact{
		OwnerId:   receiveId,
		ReceiveId: uidInt64,
		Cate:      model.ConcatCateUser,
		Memo:      memo,
	}
	if err := dao.ContactTransaction(&addContact1, &addContact2); err != nil {
		return common.Response(common.ERROR, "好友添加失败", data)
	}

	return common.Response(code, "好友添加成功", data)
}

type friendData struct {
	Id           int64  `json:"id"`
	Mobile       string `json:"mobile"`
	Avatar       string `json:"avatar"`
	Sex          int8   `json:"sex"`
	Nickname     string `json:"nickname"`
	Memo         string `json:"memo"`
	CreateAt     int64  `json:"create_at"`
	MessageTotal int64  `json:"message_total"`
}

// UserListService 好友列表
func UserListService(ctx context.Context, c *app.Context) any {

	// 创建返回信息
	resultData := make(map[string]any)
	code := common.SUCCESS

	// 参数
	var page int
	var err error
	if page, err = strconv.Atoi(c.PostForm("page")); err != nil {
		page = 1
	}
	if page <= 0 {
		page = 1
	}
	var pageSize int
	if pageSize, err = strconv.Atoi(c.PostForm("pageSize")); err != nil {
		pageSize = 100
	}

	// uid
	uid := c.UserInfo["uid"]

	// 查询列表
	// where := "status = ? and age > ?"
	// args := []any{"1", "20"}
	where := "contact.owner_id = ? and contact.cate = ?"
	args := []any{uid, model.ConcatCateUser}
	offset := (page - 1) * pageSize
	limit := pageSize
	userList, total := dao.UserJoinContactList(limit, offset, where, args...)
	//log.Printf("userlist: %#v, total: %#v", userList, total)

	var resultList []friendData
	resultList = make([]friendData, 0)
	result := friendData{}
	for _, item := range *userList {
		result.Id = item.Id
		result.Mobile = item.Mobile
		result.Avatar = item.Avatar
		result.Sex = item.Sex
		result.Nickname = item.Nickname
		result.Memo = item.Memo
		result.CreateAt = item.CreateAt
		result.MessageTotal = 0
		resultList = append(resultList, result)
	}
	resultData["list"] = resultList
	resultData["page"] = service.PagesService(page, pageSize, total)
	//log.Printf("pages: %#v", resultData)

	return common.Response(code, common.GetMsg(code), resultData)
}
